iT邦幫忙

2023 iThome 鐵人賽

DAY 25
0
Software Development

LeetCode-30 Days of JavaScript系列 第 25

LeetCode JS30-Day25 | 2722. Join Two Arrays by ID 根據ID合併兩個陣列

  • 分享至 

  • xImage
  •  

LeetCode JS30-Day25 | 2722. Join Two Arrays by ID

Description❓

Given two arrays arr1 and arr2, return a new array joinArray.
All the objects in each of the two inputs arrays will contain an id field that has an integer value.
joinArray is an array formed by merging arr1 and arr2 based on their id key.
The length of joinArray should be the length of unique values of id.
The returned array should be sorted in ascending order based on the id key.

If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.
If two objects share an id, their properties should be merged into a single object:
- If a key only exists in one object, that single key-value pair should be included in the object.
- If a key is included in both objects, the value in the object from arr2 should override the value from arr1.

給定兩個陣列 arr1arr2作為參數,回傳一個新陣列 joinArray
兩個陣列中的所有物件元素都包含一個具有整數值的 id 屬性。
joinArray 是根據 arr1arr2id 鍵合併而成的陣列。
joinArray 陣列長度應該是 id 的唯一值的長度。
回傳的陣列應根據 id 鍵按升序排序。

如果給定 id 存在於一個陣列中,但另一個陣列中不存在,則具有該 id 的單一物件應包含在結果陣列中而不進行修改。
如果兩個物件元素具有相同 id,它們的屬性值應該合併到一個物件中:
- 如果一個鍵僅存在於一個物件中,則該物中應包含該單一鍵值對。
- 如果兩個物件中都包含同一個鍵,則 arr2 物件的值應覆寫 arr1 中的值。

Input: 
arr1 = [{"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}]
arr2 = [{"id": 1, "b": {"c": 84}, "v": [1, 3]}]
Output: [{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48}]

Points

Solution✍️

[ ▶️挑戰這一題 ][ 本日代碼 ]

宣告 joinedArray空物件,我們要利用物件鍵值對的特性去確保'id'的唯一值,
最後return的時候 再利用Object.values()將物件的值轉回陣列。

const join = function (arr1, arr2) {
    const joinedArray = {};
    //arr1 = [ {"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}]
    arr1.forEach(item => {
        joinedArray[item.id] = item;
    });

    //處理arr2以及合併邏輯
    //arr2 = [ {"id": 1, "b": {"c": 84}, "v": [1, 3]}]
    arr2.forEach(item => {
        //如果存在覆寫原先數值
        //joinedArray[1]
        if (joinedArray[item.id]) {
            // Object.keys()
            // let item = { "id": 1, "b": { "c": 84 }, "v": [1, 3] }
            // Object.keys(item) == ['id', 'b', 'v']
            Object.keys(item).forEach(key => {
                //joinedArray[1]["id"] = item["id"] = 1
                //joinedArray[1]["b"]  = item["b"]  = { "c": 84 }
                //joinedArray[1]["v"]  = item["v"]  = [1, 3]..
                joinedArray[item.id][key] = item[key];
            });
        } else {
            joinedArray[item.id] = item;
        }
    });

    //joinedArray = {"1":{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48},}
    //Object.values(joinedArray)=[{"id": 1, "b": {"c": 84}, "v": [1, 3], "y": 48},}]
    return Object.values(joinedArray);
};

Testcase

let arr1 = [
    { "id": 1, "x": 1 },
    { "id": 2, "x": 9 }
]
let arr2 = [ { "id": 3, "x": 5 } ]
console.log(JSON.stringify(join(arr1, arr2)))
//output: [{"id":1,"x":1},{"id":2,"x":9},{"id":3,"x":5}]
let arr1 = [
    {"id": 1, "x": 2, "y": 3},
    {"id": 2, "x": 3, "y": 6}
], 
let arr2 = [
    {"id": 2, "x": 10, "y": 20},
    {"id": 3, "x": 0, "y": 0}
]
console.log(JSON.stringify(join(arr1, arr2)))
//output:[{"id":1,"x":2,"y":3},{"id":2,"x":10,"y":20},{"id":3,"x":0,"y":0}]
let arr1 = [{"id": 1, "b": {"b": 94},"v": [4, 3], "y": 48}]
let arr2 = [{"id": 1, "b": {"c": 84}, "v": [1, 3]}]
console.log(JSON.stringify(join(arr1, arr2)))
//output:[{"id":1,"b":{"c":84},"v":[1,3],"y":48}]

上一篇
LeetCode JS30-Day24 | 2724. Sort By 排序
下一篇
LeetCode JS30-Day26 | 2625. Flatten Deeply Nested Array 扁平化嵌套陣列
系列文
LeetCode-30 Days of JavaScript30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言